package com.idna.wsconsumer.http;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * This is a standalone client that can send and receive SOAP messages
 * via an HTTP connection. This aims to incorporate bean definitions
 * by referring to a Spring configuration file. 
 * 
 * @author kan.sun
 * 
 */
public class HttpUrlClient implements Runnable
{
	//private final static int REQUEST_POST_ERR = -1;
	//private final static int RESPONSE_GET_ERR = -2;
	//public static final String XML_REQUEST = "H:/MyWorkspace/netIdClient/src/main/resources/NetIDXMLRequest.xml";
	public final static String CFG = "H:/MyCodeBase/wsdlconsumer/netidservice/resource/applicationContext.xml";
	public void run()
	{
		final String THREAD_ID = Thread.currentThread().getName();
		try
		{
			File cfgFile = new File(CFG);
			if (cfgFile.exists() && cfgFile.canRead())
			{
				System.out.println(THREAD_ID + "-> Loading client bean...");
				ApplicationContext ctx = new FileSystemXmlApplicationContext(CFG);
				NetIDClientImpl client = (NetIDClientImpl) ctx.getBean("client");
				System.out.println(THREAD_ID + "-> Client bean loaded.");
				try
				{
					System.out.println(THREAD_ID + "-> Sending request...");
					client.sendRequest();
					System.out.println(THREAD_ID + "-> Request sent.");
					System.out.println(THREAD_ID + "-> Obtaining response...");
					client.printResponse(THREAD_ID);
					System.out.println(THREAD_ID + "-> Response printed");
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			else
			{
				System.err.println(THREAD_ID + "-> The application context configuration file is not accessible.");
			}
			Thread.sleep(20);
		}
		catch (InterruptedException ie)
		{
			Thread.currentThread().interrupt();
		}
	}
	public static void main(String[] args)
	{
		Thread thread1 = new Thread(new HttpUrlClient());
		thread1.start();
		
		Thread thread2 = new Thread(new HttpUrlClient());
		thread2.start();
		
		Thread thread3 = new Thread(new HttpUrlClient());
		thread3.start();
		
		Thread thread4 = new Thread(new HttpUrlClient());
		thread4.start();
	}
}
